﻿using System;
using System.Collections.Generic;
using System.Collections; // Used for stack.
using System.Linq;
using System.Runtime.InteropServices; // used for GUID
using System.Xml; // used for XMLTextReader and Writer.

// Used for webmethod to run code when browser closed
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;


// Widget namespaces
using wundergroundsample; // Kasey's Widget.
using CS310_TWidget; // Sam's Widget.
using Moon_Phase_Widget; // Michael's Widget
using steamWidget; // John's Widget
using NewRetailWidget; // Shaun's Widget
using MovieWidgetV4; //Ken's Widget
using WebApplication1; // Timon's Widget

// Webservice namespaces
using iITT.iITT_Services;

namespace iITT
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        // Load all widgets into grid with associated user name.
        string username = "Tchazzar";
        // Initialize temporaryListClass
        TemporaryList tempListClass = new TemporaryList();
            
        protected void Page_Load(object sender, EventArgs e)
        {
            // Global removeWidget_click event
            deleteButton.Click += new EventHandler(this.deleteButton_Click);


            // Initialize stack of div positions
            tempListClass.initializeStack();

            List<Widget> widget_list = getWidgets(username);
            foreach(Widget widget in widget_list)
            {
                // Gather information about widgets
                //string fileName = widget.Template.tRegName;
                string settings = widget.wSetings;
                string location = widget.wLocation;

                // Determine which widget is being used.
                //switch (widget.Template.tRegName)
                switch (widget.Template.tRegName)
                {
                    case ("CSTWidget.ascx"):
                    {
                        //// set the old widget in the temporary list.
                        //tempListClass.setTempWidget(widget);
                        //// Currently not working. Referencing wrong file and won't load.
                        //// set widget settings
                        //CSTWidget cst_widget = (CSTWidget)Page.LoadControl("~/Widgets/CSTWidget.ascx");
                        //cst_widget.settings = settings;
                        //// load widget into div
                        //loadWidgetInDiv((Control)cst_widget, location);
                        break;
                    }
                    case ("MoonPhaseWidget.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // this widget has no settings
                        MoonPhaseWidget moonphase_widget = (MoonPhaseWidget)Page.LoadControl("~/Widgets/MoonPhaseWidget.ascx");
                        // load widget into div
                        loadWidgetInDiv((Control)moonphase_widget, location);
                        break;
                    }
                    case ("NewsViewer.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // this widget has no settings
                        NewsViewer newsviewer_widget = (NewsViewer)Page.LoadControl("~/Widgets/NewsViewer.ascx");
                        // load widget into div
                        loadWidgetInDiv((Control)newsviewer_widget, location);
                        break;
                    }
                    case ("MovieWidget.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // this widget has no settings
                        MovieWidget movie_widget = (MovieWidget)Page.LoadControl("~/Widgets/MovieWidget.ascx");
                        // load widget into div
                        loadWidgetInDiv((Control)movie_widget, location);
                        break;
                    }
                    case ("RetailWidget.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // this widget has no settings
                        RetailWidget retail_widget = (RetailWidget)Page.LoadControl("~/Widgets/RetailWidget.ascx");
                        // load widget into div
                        loadWidgetInDiv((Control)retail_widget, location);
                        break;
                    }
                    case ("steamWidget.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // set widget settings
                        WebUserControl1 steam_widget = (WebUserControl1)Page.LoadControl("~/Widgets/steamWidget.ascx");
                        steam_widget.settings = settings;
                        // load widget into div
                        loadWidgetInDiv((Control)steam_widget, location);
                        break;
                    }
                    case ("Weather.ascx"):
                    {
                        // set the old widget in the temporary list.
                        tempListClass.setTempWidget(widget);
                        // set widget settings
                        Weather weather_widget = (Weather)Page.LoadControl("~/Widgets/Weather.ascx");
                        weather_widget.settings = settings;
                        // load widget into div
                        loadWidgetInDiv((Control)weather_widget, location);
                        break;
                    }
                }
            }
            iITT.iITT_Services.iITT_Services setPopup = new iITT.iITT_Services.iITT_Services();
            List<Template> list_temp = setPopup.GetTemplates().ToList();
            trial.InnerHtml += "<div id='popup_name' class='popup_block'>";
            int i = 0;
            foreach (Template temp in list_temp)
            {
                if (i == 0)
                {
                    trial.InnerHtml += "<div class='totalL'>";
                    trial.InnerHtml += "<div class='popwidgetimgL'><img src=" + imgicon(temp.tRegName) + " alt='" + temp.tDescription + "' class='thumb' /></div>";
                    trial.InnerHtml += "<div class='popwidgetbtnL'>" + widgetlink(temp.tRegName) + "</div>";
                    trial.InnerHtml += "</div>";
                    i = 1;
                }
                else
                {
                    trial.InnerHtml += "<div class='totalR'>";
                    trial.InnerHtml += "<div class='popwidgetimgR'><img src=" + imgicon(temp.tRegName) + " alt='" + temp.tDescription + "' class='thumb' /></div>";
                    trial.InnerHtml += "<div class='popwidgetbtnR'>" + widgetlink(temp.tRegName) + "</div>";
                    trial.InnerHtml += "</div>";
                    i = 0;
                }
            }
            trial.InnerHtml += "</div>";
        }

        private void loadWidgetInDiv(Control control, string location)
        {
            List<String> tempArray = new List<String>();
            tempArray.Add("0");
            tempArray.Add("1");
            tempArray.Add("2");
            tempArray.Add("3");
            tempArray.Add("4");
            tempArray.Add("5");
            tempArray.Add("6");
            tempArray.Add("7");
            tempArray.Add("8");
            tempArray.Add("9");

            // Catch invalid location name
            if (!tempArray.Contains(location))
            {
                location = "0";
            }

            int loc = Convert.ToInt32(location);
            loc = checkLocation(loc); // check if div is ok to use, if not find another spot.
            Control TemporaryControl = new Control(); // Used to load multiple instances of different widgets.

            // set widget guid
            TemporaryControl = control;
            TemporaryControl.ID = tempListClass.returnID();

            // load control into panel
            if (loc >= 1 && loc <= 9) // Control is within grid.
            {
                switch (loc)
                {
                    case (1): box1.Controls.Add(TemporaryControl); break;
                    case (2): box2.Controls.Add(TemporaryControl); break;
                    case (3): box3.Controls.Add(TemporaryControl); break;
                    case (4): box4.Controls.Add(TemporaryControl); break;
                    case (5): box5.Controls.Add(TemporaryControl); break;
                    case (6): box6.Controls.Add(TemporaryControl); break;
                    case (7): box7.Controls.Add(TemporaryControl); break;
                    case (8): box8.Controls.Add(TemporaryControl); break;
                    case (9): box9.Controls.Add(TemporaryControl); break;
                }
            }
        }

        private int checkLocation(int location)
        {
            // This method calls checkDivAvailability to see if the current location is used and valid. If it is, it cycles 
            //  through the grid to find an available spot.
            int count = 0;
            while (!checkDivAvailability(location))
            {
                location++;
                if (location > 9) location = 1;
                count++;
                // breaks from method, does not continue to try to add widget to grid. There is not enough space
                // for the widget.
                if (count > 10) return -1;
            }
            return location;
        }

        private Boolean checkDivAvailability(int location)
        {
            // Checks the current location and determines whether there is already content inside of the div.
            // If there is content, it returns false. If it is empty, it returns true. Invalid numbers are false.
            int loc = Convert.ToInt32(location);

            // box count is 1 because we use panels inside divs, the minimum count will be 1 for empty, 2+ for controls.
            // location 0 is always false, therefore will be incremented to 1.
            if (loc == 0) return false; // Exception to checking div availability. will be caught before being passed here.
            else if (loc == 1) if (box1.Controls.Count != 0) return false; else return true;
            else if (loc == 2) if (box2.Controls.Count != 0) return false; else return true;
            else if (loc == 3) if (box3.Controls.Count != 0) return false; else return true;
            else if (loc == 4) if (box4.Controls.Count != 0) return false; else return true;
            else if (loc == 5) if (box5.Controls.Count != 0) return false; else return true;
            else if (loc == 6) if (box6.Controls.Count != 0) return false; else return true;
            else if (loc == 7) if (box7.Controls.Count != 0) return false; else return true;
            else if (loc == 8) if (box8.Controls.Count != 0) return false; else return true;
            else if (loc == 9) if (box9.Controls.Count != 0) return false; else return true;
            else return false;
        }

        private List<Widget> getWidgets(string username)
        {
            iITT_Services.iITT_Services webservice = new iITT_Services.iITT_Services();
            List<Widget> widget_list = webservice.GetWidgets(username).ToList();
            return widget_list;
        }

        private Widget getWidgetInfo(string username, string currentLocation)
        {
            iITT_Services.iITT_Services webservice = new iITT_Services.iITT_Services();
            List<Widget> widget_list = webservice.GetWidgets(username).ToList();

            Widget tempWidget = new Widget();
            foreach (Widget widget in widget_list)
            {
                if (widget.wLocation == currentLocation)
                {
                    tempWidget = widget;
                }
            }
            return tempWidget;
        }

        private void deleteButton_Click(Object sender, EventArgs e)
        {
            removeWidget(username, deleteWidgetTextBox.Text);
        }

        private void removeWidget(string username, string wID)
        {
            iITT_Services.iITT_Services webservice = new iITT_Services.iITT_Services();
            webservice.RemoveWidget(username, Convert.ToInt32(wID));
        }

        public void pageClose()
        {
            List<Widget> ListToDB = new List<Widget>();
            int panelCount = 1;
            foreach (Panel box in Page.Controls)
            {
                // set the temporary widget to the old widget with this identical control.id
                Widget temp = tempListClass.getTempWidget(box.Controls[0].ID);
                temp.wLocation = panelCount.ToString();
                ListToDB.Add(temp);
                panelCount++;
                if (panelCount > 9)
                {
                    // Throw exception because there should ONLY be 9 panels within the Page.Controls.
                    IndexOutOfRangeException ex = new IndexOutOfRangeException();
                    throw ex;
                }
            }
            iITT_Services.iITT_Services webservice = new iITT_Services.iITT_Services();
            // Send the list of updated widgets to the Database.
            //webservice.AddWidget(username, ListToDB);
            // Clear the temporary list of all widgets.
            tempListClass.clearTempWidgetList();
        }

        private string imgicon(string id)
        {
            switch (id)
            {
                case ("steamWidget.ascx"): return "images/steamWidget.png";
                case ("Weather.ascx"): return "http://icons-ak.wxug.com/i/wu/wuLogoNon.png";
                case ("MoonPhaseWidget.ascx"): return "images/MoonPhase%20Widget.jpg";
                case ("MovieWidget.ascx"): return "images/MovieWidget.png";
                case ("RetailWidget.ascx"): return "images/Amazon-eBay_Widget_SS.png";
                case ("CSTWidget.ascx"): return "images/TwitterProjectSS.PNG";
                case ("NewsViewer.ascx"): return "images/WidPage.png";
            }
            return null;
        }

        private string widgetlink(string id)
        {
            switch (id)
            {
                case ("steamWidget.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/Steam Config.aspx','Steam','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("Weather.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/WeatherConfig.aspx','Weather','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("MoonPhaseWidget.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/MoonphaseConfig.aspx','MoonPhase','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("MovieWidget.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/MovieWidget.aspx','Movie','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("RetailWidget.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/RetailWidget.aspx','Amazon','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("CSTWidget.ascx"): return "<a href=\"#\" onclick=\"window.open('http://www.google.com','Twitter','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
                case ("NewsViewer.ascx"): return "<a href=\"#\" onclick=\"window.open('Configuration/NewsViewer.aspx','News','width=400,height=200')\"><img src='images/addwidget.jpg' alt='Add Widget' /></a>";
            }
            return null;
        }
    }
}